<%@ page contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket</title>

</head>
<body>
<h3>hello socket</h3>
<p>【fromId】：<div><input id="fromId" name="fromId" type="text" value="google"></div>
<p>【toId】：<div><input id="toId" name="toId" type="text" value="firefox"></div>
<p>【内容】：<div><input id="content" name="content" type="text" value="hello firefox, 这是个测试的websocket"></div>
<p>【操作】：<input type="button" onclick="openSocket()" value="开启socket" />
<p>【操作】：<input type="button" onclick="sendMessage()"value="发送消息" />
<ul id="cont"></ul>
</body>
<script type="text/javascript">


    var socket;
    function openSocket() {
        if(typeof(WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        }else{
            console.log("您的浏览器支持WebSocket");
            //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
            var fromId = document.getElementById('fromId').value;
            var socketUrl="ws://127.0.0.1:8888/webSocket/"+fromId;
            console.log(socketUrl);
            if(socket!=null){
                socket.close();
                socket=null;
            }
            socket = new WebSocket(socketUrl);
            //打开事件
            socket.onopen = function() {
                console.log("websocket已打开");
                //socket.send("这是来自客户端的消息" + location.href + new Date());
            };
            //获得消息事件
            socket.onmessage = function(msg) {
                var serverMsg = "收到服务端信息：" + msg.data;
                console.log(serverMsg);
                var message=JSON.parse(msg.data);
                var node=document.createElement("LI");
                var textnode=document.createTextNode(message.content);
                node.appendChild(textnode);
                document.getElementById("cont").appendChild(node);
            };
            //关闭事件
            socket.onclose = function() {
                console.log("websocket已关闭");
            };
            //发生了错误事件
            socket.onerror = function() {
                console.log("websocket发生了错误");
            }
        }
    }
    function sendMessage() {
        if(typeof(WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        }else {
            // console.log("您的浏览器支持WebSocket");
            var fromId = document.getElementById('fromId').value;
            var toId = document.getElementById('toId').value;
            var content = document.getElementById('content').value;
            var jsonMsg={fromId:fromId,toId:toId,content:content,sendMsgType:"dialog"};
            console.log(jsonMsg);
            socket.send(JSON.stringify(jsonMsg));
        }
    }

</script>
</html>
